import React, { useState, useRef } from 'react';
import { HotTable } from '@handsontable/react';
import Handsontable from 'handsontable';
import { Card, Button, Space, Upload, message } from 'antd';
import { EditableProTable } from '@ant-design/pro-table';
import FileSaver from 'file-saver';

export default function Grid() {
  // HandsonTable 相关 ---------------------
  // 初始化数据
  const initData = Handsontable.helper.createSpreadsheetData(20, 20);
  // 表格的数据
  const [gridData, setGridData] = useState(initData);
  // 合并的单元格
  const [mergeCells, setMergeCells] = useState([
    { row: 9, col: 9, rowspan: 2, colspan: 2 },
  ]);
  // 记录单元格颜色
  const [cell, setCell] = useState([
    {
      row: 0,
      col: 5,
      className: 'red',
    },
    {
      row: 0,
      col: 14,
      className: 'green',
    },
    {
      row: 5,
      col: 0,
      className: 'yellow',
    },
    {
      row: 5,
      col: 19,
      className: 'purple',
    },
    {
      row: 14,
      col: 0,
      className: 'pink',
    },
    {
      row: 14,
      col: 19,
      className: 'orange',
    },
    {
      row: 19,
      col: 5,
      className: 'grey',
    },
    {
      row: 19,
      col: 14,
      className: 'blue',
    },
  ]);
  // HandsonTable 的 settings
  const [tableSettings, setTableSettings] = useState(() => {
    const initialState = {
      data: gridData,
      colHeaders: true,
      rowHeaders: true,
      manualColumnResize: true, // 列拖拽改变大小
      manualRowResize: true, // 行拖拽改变大小
      height: 'auto',
      colWidths: 35,
      rowHeights: 25,
      observeChanges: false,
      // copyable: true,
      mergeCells,
      afterChange: function (changes, source) {
        if (source === 'MergeCells') {
          const row = changes[0][0];
          const col = changes[0][1];
          const rowspan = changes[3][0] - row + 1;
          const colspan = changes[3][1] - col + 1;
          mergeCells.push({ row, col, rowspan, colspan });
          setMergeCells(mergeCells);
        }

        setGrid(this);
      },
      cell,
      // cells: (row, col, prop) => {
      //     console.log(row, col, prop)
      // },
      contextMenu: {
        items: {
          mergeCells: 'mergeCells',
          separator: Handsontable.plugins.ContextMenu.SEPARATOR,
          red: {
            name: 'red',
            callback: function (_, range) {
              setColor(range, this, 'red');
            },
          },
          green: {
            name: 'green',
            callback: function (_, range) {
              setColor(range, this, 'green');
            },
          },
          yellow: {
            name: 'yellow',
            callback: function (_, range) {
              setColor(range, this, 'yellow');
            },
          },
          purple: {
            name: 'purple',
            callback: function (_, range) {
              setColor(range, this, 'purple');
            },
          },
          pink: {
            name: 'pink',
            callback: function (_, range) {
              setColor(range, this, 'pink');
            },
          },
          orange: {
            name: 'orange',
            callback: function (_, range) {
              setColor(range, this, 'orange');
            },
          },
          grey: {
            name: 'grey',
            callback: function (_, range) {
              setColor(range, this, 'grey');
            },
          },
          blue: {
            name: 'blue',
            callback: function (_, range) {
              setColor(range, this, 'blue');
            },
          },
          separator2: Handsontable.plugins.ContextMenu.SEPARATOR,
          clear: {
            name: 'clear color',
            callback: function (_, range) {
              setColor(range, this, 'white');
            },
          },
        },
      },
      licenseKey: 'non-commercial-and-evaluation',
    };

    return initialState;
  });
  // HandsonTable 的 this 对象
  const [grid, setGrid] = useState(initData);
  // HandsonTable 相关 结束 ---------------------

  // EditableProTable 相关 ---------------------
  const [tableData, setTableData] = useState([]);
  const [editableKeys, setEditableRowKeys] = useState([]);
  const hotTableComponent = useRef(null);
  // EditableProTable 相关 结束 ---------------------

  // 是否允许执行 记录 功能
  const [recordFlag, setRecordFlag] = useState(false);

  const setColor = (range, instance, className) => {
    const { start, end } = range[0];
    for (let row = start.row; row <= end.row; row += 1) {
      for (let col = start.col; col <= end.col; col += 1) {
        instance.setCellMeta(row, col, 'className', className);
        cell.push({
          row,
          col,
          className,
        });
        setCell(cell);
      }
    }
    instance.render();
    instance.resumeRender();
    setGrid(instance);
  };

  /**
   * 遍历 HandsonTable 中的记录计算结果
   */
  const calculate = () => {
    console.log(cell);
    const result = {};
    const resultData = [];
    // console.log(grid.getCellMeta(0, 0)['className']);
    // console.log(grid.getDataAtCell(9, 10) || 0);
    // console.log("calculate", grid.getData(0, 5, 0, 5));

    for (let rowIndex = 0; rowIndex < 20; rowIndex += 1) {
      for (let colIndex = 0; colIndex < 20; colIndex += 1) {
        const color = grid.getCellMeta(rowIndex, colIndex).className;
        const score = grid.getData(
          rowIndex,
          colIndex,
          rowIndex,
          colIndex
        )[0][0];

        if (color in result) {
          result[color] += Number(score) || 0;
        } else {
          result[color] = Number(score) || 0;
        }
      }
    }

    for (let key in result) {
      if (key !== 'undefined' && key !== 'white') {
        const currentData = tableData.filter((element) => {
          return element.color === key;
        });

        let guildName = key;
        let currentScore = 0;
        if (currentData.length > 0) {
          guildName = currentData[0].guildName;
          currentScore = Number(currentData[0].currentScore) || 0;
        }
        // console.log("currentData", currentData)
        const addScore = Number(result[key]) || 0;
        const afterScore = currentScore + result[key];
        resultData.push({
          color: key,
          guildName,
          currentScore,
          addScore,
          afterScore,
        });
      }
    }

    setRecordFlag(true);
    setTableData(resultData);

    // hotTableComponent.current.hotInstance.loadData([]);
  };

  /**
   * 下方 EditableProTable 字段定义
   */
  const columns = [
    {
      title: '颜色',
      dataIndex: 'color',
      editable: () => false,
    },
    {
      title: '工会名称',
      dataIndex: 'guildName',
    },
    {
      title: '当前分数',
      dataIndex: 'currentScore',
      defaultSortOrder: 'descend',
      sorter: (a, b) => a.currentScore - b.currentScore,
    },
    {
      title: '本轮增加分数',
      dataIndex: 'addScore',
      editable: () => false,
      defaultSortOrder: 'descend',
      sorter: (a, b) => a.currentScore - b.currentScore,
    },
    {
      title: '本轮结算分数',
      dataIndex: 'afterScore',
      editable: () => false,
      defaultSortOrder: 'descend',
      sorter: (a, b) => a.afterScore - b.afterScore,
    },
    {
      title: '操作',
      valueType: 'option',
      width: 200,
      render: (text, record, _, action) => [
        // eslint-disable-next-line jsx-a11y/anchor-is-valid
        <a
          key="editable"
          onClick={() => {
            action?.startEditable?.(record.color);
          }}
        >
          编辑
        </a>,
      ],
    },
  ];

  /**
   * 将 afterScore 赋值给 currentScore 并清空 afterScore
   */
  const record = () => {
    // console.log(tableData)
    if (!recordFlag) {
      message.warning({
        content: '请先计算后再记录',
        style: {
          marginTop: '50vh',
        },
      });
      return;
    }

    const result = tableData.map((element) => {
      return { ...element, currentScore: element.afterScore, afterScore: 0 };
    });
    // console.log(result)
    setTableData(result);
    setRecordFlag(false);
  };

  const importProps = {
    onChange: (info) => {
      const fileReader = new FileReader();
      fileReader.onload = (event) => {
        const { result } = event.target;
        const data = JSON.parse(result);

        const { savedGridData, savedMergeCells, savedCell, savedTableData } =
          data;

        // 设置 cell 的底色
        cell.splice(0, cell.length);
        savedCell.forEach((element) => {
          cell.push(element);
          grid.setCellMeta(
            element.row,
            element.col,
            'className',
            element.className
          );
        });
        setCell(cell);

        // 设置 cell 的值
        for (let row = 0; row < 20; row++) {
          for (let col = 0; col < 20; col++) {
            gridData[row][col] = savedGridData[row][col];
          }
        }
        setGridData(gridData);

        // 设置 合并单元格
        console.log(mergeCells);
        console.log(savedMergeCells);
        mergeCells.splice(0, mergeCells.length);
        savedMergeCells.forEach((element) => {
          mergeCells.push(element);
        });
        setMergeCells(mergeCells);
        console.log(hotTableComponent);

        // 设置 计算结果
        setTableData(savedTableData);

        // 重新渲染
        grid.render();
      };
      // 读取文件
      fileReader.readAsText(info.file);
    },
    showUploadList: false,
    accept: '.json',
    beforeUpload: () => false,
  };

  const exportData = () => {
    const str = JSON.stringify({
      savedGridData: gridData,
      savedMergeCells: mergeCells,
      savedCell: cell,
      savedTableData: tableData,
    });
    let blob = new Blob([str], {
      type: 'text/plain;charset=utf-8',
    });
    FileSaver.saveAs(blob, 'test.json');
  };

  return (
    <>
      <Card
        title="编辑地图"
        extra={
          <Space>
            <Upload {...importProps}>
              <Button type="primary">导入</Button>
            </Upload>
            <Button type="primary" onClick={exportData}>
              导出
            </Button>
          </Space>
        }
      >
        <HotTable ref={hotTableComponent} settings={tableSettings} />
      </Card>
      {/* <Card
        title="结果计算"
        extra={
          <Space>
            <Button type="primary" onClick={calculate}>
              开始计算
            </Button>
            <Button type="primary" onClick={record}>
              记录
            </Button>
          </Space>
        }
      >
        <EditableProTable
          rowKey="color"
          maxLength={5}
          // recordCreatorProps={{ record: () => ({ id: (Math.random() * 1000000).toFixed(0) }) }}
          recordCreatorProps={false}
          columns={columns}
          request={async () => ({
            data: tableData,
            total: 3,
            success: true,
          })}
          value={tableData}
          onChange={setTableData}
          editable={{
            type: 'multiple',
            editableKeys,
            onSave: async (rowKey, data, row) => {
              // setGuild({});
              console.log(rowKey, data, row);
            },
            onChange: setEditableRowKeys,
          }}
        />
      </Card> */}
    </>
  );
}
